package api

import (
	"sync"
	"time"
)

type RequestLimiter struct {
	Interval     time.Duration
	MaxCount     int
	Lock         sync.Mutex
	RequestCount int
}

func NewRequestLimiter(interval time.Duration, maxCount int) *RequestLimiter {
	requestLimiter := &RequestLimiter{
		Interval: interval,
		MaxCount: maxCount,
	}
	go func() {
		ticker := time.NewTicker(interval)
		for {
			<-ticker.C
			requestLimiter.Lock.Lock()
			requestLimiter.RequestCount = 0
			requestLimiter.Lock.Unlock()
		}
	}()
	return requestLimiter
}

func (_this *RequestLimiter) Increase() {
	_this.Lock.Lock()
	defer _this.Lock.Unlock()
	_this.RequestCount += 1
}

func (_this *RequestLimiter) IsAvailable() bool {
	_this.Lock.Lock()
	defer _this.Lock.Unlock()

	return _this.RequestCount < _this.MaxCount
}
